package com.runa.monitor.platinterface.netservice.handler;

import com.runa.persistence.util.LogUtil;
import com.runa.protocol.dto.DtuReportAck;
import com.runa.protocol.dto.IInterData;
import com.runa.protocol.util.ByteUtil;
import com.runa.rccprotocol.dto.ConcentratorRequestData;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author zhuj
 */
@ChannelHandler.Sharable
public class DatagramEncoder extends MessageToMessageEncoder<IInterData> {

    private static final Logger logger = LoggerFactory.getLogger(DatagramEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, IInterData msg, List<Object> list) {
        String addr = null;
        String remote = null;
        if (msg instanceof DtuReportAck) {
            DtuReportAck ack = (DtuReportAck) msg;
            if (ack.getAddr() != null) {
                addr = ack.getAddr();
                final AttributeKey<DatagramPacket> packetAttributeKey = AttributeKey.valueOf(addr);
                DatagramPacket packet = ctx.channel().attr(packetAttributeKey).get();
                if (packet != null) {
                    list.add(new DatagramPacket(Unpooled.wrappedBuffer(ack.getData()), packet.sender()));
                    remote = packet.sender().toString();
                    LogUtil.info(addr, ack.getData(), "响应");
                }
            }
        } else if (msg instanceof ConcentratorRequestData) {
            ConcentratorRequestData requestData = (ConcentratorRequestData)msg;
            addr = requestData.getAddress();
            final AttributeKey<DatagramPacket> packetAttributeKey = AttributeKey.valueOf(addr);
            DatagramPacket packet = ctx.channel().attr(packetAttributeKey).get();
            if (packet != null) {
                list.add(new DatagramPacket(Unpooled.wrappedBuffer((byte[]) msg.getData()), packet.sender()));
                remote = packet.sender().toString();
            }
        }
        logger.debug("DatagramEncoder To {}:{}, remote: {}", addr, ByteUtil.byteToHexString((byte[]) msg.getData()), remote);
    }
}
